<!doctype html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport"
          content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>贪吃蛇</title>
    <style>
        *{
            padding: 0;
            margin: 0;
        }
        #map{
            width: 400px;
            height: 400px;
            background-color: black;
            position: relative;
        }
    </style>
</head>
<body>
<div id="map"></div>
<script>
    class Map{
        constructor(el, rect = 10) {
            this.el = el
            this.rect = rect
            this.data = []
            this.rows = Math.ceil(Map.getStyle(el,'height') / rect)
            this.cells = Math.ceil(Map.getStyle(el,'width') / rect)
            Map.setStyle(el,'height',this.rows*rect)
            Map.setStyle(el,'width',this.cells*rect)
        }
        static getStyle(el,attr){
            return parseFloat(getComputedStyle(el)[attr])
        }
        static setStyle(el,attr,val){
            return el.style[attr] = val + 'px'
        }

        // 通过setData，往面板里面添加数据
        setData(newData){
            this.data = this.data.concat(newData)
        }
        clearData(){
            this.data.length = 0
        }
        include({x,y}){
            return !!this.data.find(item=> item.x === x && item.y === y)
        }
        render(){
            this.el.innerHTML = this.data.map(item=>{
                return `<span style="position: absolute;left: ${item.x*this.rect}px;top: ${item.y*this.rect}px;
                            width: ${this.rect}px;height: ${this.rect}px;background-color: ${item.color}"></span>`
            }).join("")
        }
    }
    // 食物类
    class Food{
        constructor(map, colors = ["red","pink","yellow","blue"]) {
            this.map = map
            this.colors = colors
            this.data = null
        }
        create(){
            let x = Math.floor(Math.random()*this.map.cells)
            let y = Math.floor(Math.random()*this.map.rows)
            let color = this.colors[Math.ceil(Math.random()*this.colors.length-1)]
            this.data = {x,y,color}
            console.log(this.data)
            // 如果重合，就重新生成一个点
            if(this.map.include(this.data)){
                this.create()
            }
        }
    }
    {
        let map = document.getElementById('map')
        let gameMap = new Map(map,40)
        let gameFood = new Food(gameMap)
        gameFood.create()
        // setInterval(()=>{
        //     gameFood.create()
        //     gameMap.setData(gameFood.data)
        //     gameMap.render()
        // },200)
    }
</script>
</body>
</html>